package com.baosight.xinreport.sql.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baosight.xinreport.sql.mapper.DynamicTableSqlMapper;
import com.baosight.xinreport.sql.service.IRunSqlService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class RunSqlServiceImpl implements IRunSqlService {
    @Value("${mybatis-plus.configuration.database-id}")
    private String database;

    public static final String  PARAMETER_SYMBOL = "#\\{([^}]*)}";

    @Resource
    DynamicTableSqlMapper dynamicTableSqlMapper;

    /**
     * 执行sql，将sql转换为page
     * @param page
     * @param sql select * from table1 where table1.abc=#{}
     * @param queryMap
     * @return
     */
    @Override
    public Page<Map> runQuerySqlPage(Page page, String sql, Map queryMap) {
        String selectSql = "";
        String countSql = "";
        String querySql = sqlFromPage(selectSql,page);
        querySql = replaceParameters(querySql,queryMap);
        List<Map> list = dynamicTableSqlMapper.queryDynamicTableData(querySql);
        page.setRecords(list);
        int count = dynamicTableSqlMapper.countDynamicTableData(countSql);
        page.setTotal(count);
        return page;
    }

    /**
     * 执行sql ，将sql转换为 list数据
     * @param sql
     * @param queryMap
     * @return
     */
    @Override
    public List<Map> runQuerySql(String sql, Map queryMap) {
        String querySql = replaceParameters(sql,queryMap);
        List<Map> list = dynamicTableSqlMapper.queryDynamicTableData(querySql);
        return list;
    }

    /**
     * sql分页
     * @param sql
     * @param page
     * @return
     */
    private String sqlFromPage(String sql, Page page){
        String limitSql = "";
        if(null!=page) {
            if (database.toLowerCase().equals("mysql")) {
                limitSql = " limit " + (page.getCurrent() - 1) + " , " + page.getSize();
                return sql+ limitSql;
            }else if(database.toLowerCase().equals("db2")){
                limitSql = " limit " + (page.getCurrent() - 1) + " , " + page.getSize();
                return sql+ limitSql;
            }
        }
        return sql+ limitSql;
    }

    /**
     * 替换参数
     * @param sql
     * @param parameters
     * @return
     */
    public  String replaceParameters(String sql, Map<String, Object> parameters) {
        Pattern pattern = Pattern.compile(PARAMETER_SYMBOL);
        Matcher matcher = pattern.matcher(sql);
        StringBuffer result = new StringBuffer();

        while (matcher.find()) {
            String key = matcher.group(1);
            if (parameters.containsKey(key)) {
                String replacement = parameters.get(key).toString();
                matcher.appendReplacement(result, replacement);
            } else {
                throw new IllegalArgumentException("Parameter not found for key: " + key);
            }
        }
        matcher.appendTail(result);
        return result.toString();
    }

}
